package com.labbit.platform.commons.exception;

import com.labbit.platform.commons.domain.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @Description 统一异常处理
 * @Date 2019-07-28 16:09
 * @Author CHEN YU
 **/
@RestControllerAdvice
@Slf4j
public class ControllerExceptionHandler {

    private static final String PARAM_ERROR = "请求参数错误";
    private static final String CONTENT_TYPE_ERROR = "Content type 错误。";
    private static final String SYSTEM_ERROR = "操作错误，请重试。";
    private static final String PAGE_NOT_FOUNT = "请求地址错误";
    private static final String REQUEST_METHOD_ERROR = "请求方法错误";

    /**
     * 处理参数异常 bean
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    public Result methodArgumentNotValidException(MethodArgumentNotValidException ex) {
        List<String> result = new ArrayList<>();
        ex.getBindingResult().getAllErrors().forEach(error -> result.add(error.getDefaultMessage()));
        return Result.fail(HttpStatus.BAD_REQUEST.value(), StringUtils.join(result, ","));
    }

    /**
     * 处理参数异常 方法级别异常拦截
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    public Result constraintViolationException(ConstraintViolationException ex) {
        List<String> result = new ArrayList<>();
        Set<ConstraintViolation<?>> cves = ex.getConstraintViolations();
        for (ConstraintViolation<?> constraintViolation : cves) {
            result.add(constraintViolation.getMessage());
        }
        return Result.fail(HttpStatus.BAD_REQUEST.value(), StringUtils.join(result, ","));
    }

    /**
     * content type 错误的情况
     */
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    public Result httpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException ex) {
        log.info(CONTENT_TYPE_ERROR, ex);
        return Result.fail(HttpStatus.BAD_REQUEST.value(), CONTENT_TYPE_ERROR);
    }

    /**
     * 前端传递参数格式不符合的情况
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    public Result httpMessageNotReadableException(HttpMessageNotReadableException ex) {
        log.info(PARAM_ERROR, ex);
        return Result.fail(HttpStatus.BAD_REQUEST.value(), PARAM_ERROR);
    }

    /**
     * 前端请求方法不符合的情况
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    public Result httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException ex) {
        log.info(REQUEST_METHOD_ERROR, ex);
        return Result.fail(HttpStatus.BAD_REQUEST.value(), REQUEST_METHOD_ERROR);
    }

    /**
     * 自定义业务异常信息
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(code = HttpStatus.OK)
    public Result businessException(BusinessException ex) {
        log.info(ex.getMessage(), ex);
        return Result.fail(ex.getExceptionMessage().getCode(), ex.getExceptionMessage().getMessage());
    }

    /**
     * 后端验证错误
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    public Result bindException(BindException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        List<String> result = new ArrayList<>();
        for (ObjectError error : allErrors) {
            result.add(error.getDefaultMessage());
        }
        return Result.fail(HttpStatus.BAD_REQUEST.value(), StringUtils.join(result, ","));
    }

    /**
     * 其他异常信息 500
     */
    @ExceptionHandler(Throwable.class)
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    public Result commonException(Throwable ex) {
        log.error("system error!!!", ex);
        return Result.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), SYSTEM_ERROR);
    }

    /**
     * 404
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(code = HttpStatus.NOT_FOUND)
    public Result noHandlerFoundException(NoHandlerFoundException ex) {
        log.info(PAGE_NOT_FOUNT, ex);
        return Result.fail(HttpStatus.NOT_FOUND.value(), PAGE_NOT_FOUNT);
    }

    /**
     * 401
     */
    @ExceptionHandler(UnauthorizedException.class)
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    public Result unauthorizedException(UnauthorizedException ex) {
        log.info(ex.getExceptionMessage().getMessage(), ex);
        return Result.fail(HttpStatus.UNAUTHORIZED.value(),  ex.getExceptionMessage().getMessage());
    }

    /**
     * 403
     */
    @ExceptionHandler(ForbiddenException.class)
    @ResponseStatus(code = HttpStatus.FORBIDDEN)
    public Result forbiddenException(ForbiddenException ex) {
        log.info(ex.getExceptionMessage().getMessage(), ex);
        return Result.fail(HttpStatus.FORBIDDEN.value(), ex.getExceptionMessage().getMessage());
    }
}
